File Handling
IO Streams
and Files
Concept
of IO Streams
Streams in Java
A
stream is a sequence of data. In Java, a stream is composed of bytes. It's
called a stream because it is a continuous flow of data.
1. Java treats flow of data as stream.
2. Java streams are classified into two basic types: input stream and
output stream.
3. The java.io package contains a large number of stream classes to support
the streams.
This package provides system
input and output through data streams, serialization and the file system.
1. Java I/O (Input and Output) is
used to process the input and produce the output.
2. Java uses the concept of a stream
to make I/O operation fast. The java.io package contains all the classes
required for input and output operations.
3. We can perform file handling in
Java by java.io API.
Interfaces
in Package java.io
Interface |
Description |
A Closeable is
a source or destination of data that can be closed. |
|
The DataInput interface
provides for reading bytes from a binary stream and reconstructing from them
data in any of the Java primitive types. |
|
The DataOutput interface
provides for converting data from any of the Java primitive types to a series
of bytes and writing these bytes to a binary stream. |
|
Only
the identity of the class of an Externalizable instance is written in the
serialization stream and it is the responsibility of the class to save and
restore the contents of its instances. |
|
A
filter for abstract pathnames. |
|
Instances
of classes that implement this interface are used to filter filenames. |
|
A Flushable is
a destination of data that can be flushed. |
|
ObjectInput
extends the DataInput interface to include the reading of objects. |
|
Callback
interface to allow validation of objects within a graph. |
|
ObjectOutput
extends the DataOutput interface to include writing of objects. |
|
Constants
written into the Object Serialization Stream. |
|
Serializability
of a class is enabled by the class implementing the java.io.Serializable
interface. |
Exceptions
in Package java.io
I-O stream
classes in Java
Java provides java.io package which
contains a large number of stream classes to process all types of data:
Ø Byte stream classes
•
Support
for handling I/O operations on bytes
Ø Character stream classes
•
Supports
for handling I/O operations on characters
Methods in Byte Stream (input) classes
Method |
Description |
read( ) |
Read a byte from the input stream |
read(byte b[ ]) |
Read an array of bytes into b |
read(byte b[ ], int n, int m) |
Reads m bytes into b starting from nth byte |
available( ) |
Gives number of bytes available in the input |
skip(n) |
Skips over n bytes from the input stream |
reset( ) |
Goes back to the beginning of the stream |
close( ) |
Close the input steam |
Example:
DataInputStream
readShort( ) |
readDouble( ) |
readInt( ) |
readLine( ) |
readLong( ) |
readChar( ) |
readFloat( ) |
readBoolean( ) |
readUTF( ) |
Methods in Byte Stream (output) classes
Method |
Description |
write (int b ) |
Write a byte from the input stream |
write (byte b[ ]) |
Write all bytes in the array b to the output
steam |
write (byte b[ ], int n, int m) |
Write m bytes from array b starting from nth byte |
close( ) |
Close the output stream |
flush( ) |
Flushes the output stream |
Example:
DataOutputStream
writeShort( ) |
writeDouble( ) |
writeInt( ) |
writeLine( ) |
writeLong( ) |
writeChar( ) |
writeFloat( ) |
WriteBoolean( ) |
writeUTF( ) |
|
Methods in Character Stream (reader) classes
Method |
Description |
close() |
Closes the stream and releases any system
resources associated with it. |
mark(int readAheadLimit) |
Tells whether this stream supports the mark()
operation. |
markSupported() |
Tells whether this stream supports the mark()
operation. |
read() |
Reads a single character. |
read(char[] cbuf) |
Reads characters into an array. |
read(char[] cbuf, int off, int len) |
Reads characters into a portion of an array. |
read(CharBuffer target) |
Attempts to read characters into the specified
character buffer. |
ready() |
Tells whether this stream is ready to be read. |
reset() |
Resets the stream. |
skip(long n) |
Skips characters. |
Methods in Character Stream (Writer) classes
Method |
Description |
append(char c) |
Appends
the specified character to this writer. |
append(CharSequence csq) |
Appends
the specified character sequence to this writer. |
append(CharSequence
csq, int start, int end) |
Appends
a subsequence of the specified character sequence to this writer. |
close() |
Closes
the stream, flushing it first. |
flush() |
Flushes the stream. |
write(char[] cbuf) |
Writes
an array of characters. |
write(char[]
cbuf, int off, int len) |
Writes
a portion of an array of characters. |
write(int c) |
Writes a single character. |
write(String str) |
Writes a string. |
write(String
str, int off, int len) |
Writes
a portion of a string. |
IO with Byte
Streams
Byte Stream Classes are used to read bytes from an
input stream and write bytes to an output stream.
Working of byte stream class
Byte Stream classes are divided in two groups:
•
InputStream
classes: These classes are
subclasses of an abstract class InputStream and they are used to read bytes
from a source (file, memory, or console).
•
OutputStream classes: These classes are subclasses of an abstract class
OutputStream and they are used to write bytes to a destination (file, memory or
console).
Notes:
•
Programs
use byte streams to perform input and output of 8-bit bytes.
•
All byte
stream classes are descended from InputStream and OutputStream.
•
There are
many byte stream classes. To demonstrate how byte streams work, we'll focus on the
file I/O byte streams, FileInputStream and FileOutputStream.
•
Other
kinds of byte streams are used in much the same way; they differ mainly in the
way they are constructed.
Java Input Stream Classes
Note:
InputStream
class is an abstract class. It is the superclass of all classes representing an
input stream of bytes.
public abstract class InputStream extends
Object implements Closeable
Classes under InputStream class
Class |
Description |
A BufferedInputStream adds
functionality to another input stream-namely, the ability to buffer the input
and to support the mark and reset methods. |
|
A ByteArrayInputStream contains
an internal buffer that contains bytes that may be read from the stream. |
|
A data input stream lets an
application read primitive Java data types from an underlying input stream in
a machine-independent way. |
|
A FileInputStream obtains
input bytes from a file in a file system. |
|
A piped input stream should be
connected to a piped output stream; the piped input stream then provides
whatever data bytes are written to the piped output stream. |
|
An ObjectInputStream deserializes
primitive data and objects previously written using an ObjectOutputStream. |
available() |
Returns an estimate of the number
of bytes that can be read (or skipped over) from this input stream without
blocking by the next invocation of a method for this input stream. |
close() |
Closes this input stream and
releases any system resources associated with the stream. |
mark(int readlimit) |
Marks the current position in this
input stream. |
markSupported() |
Tests if this input stream
supports the mark and reset methods. |
read() |
Reads the next byte of data from
the input stream. |
read(byte[] b) |
Reads some number of bytes from
the input stream and stores them into the buffer array b. |
read(byte[] b, int off, int len) |
Reads up to len bytes of
data from the input stream into an array of bytes. |
reset() |
Repositions this stream to the
position at the time the mark method was last called on this input
stream. |
skip(long n) |
Skips over and
discards n bytes of data from this input stream. |
InputStream
classes is used to read 8-bit bytes and supports a number of input-related
methods
•
Reading
bytes
•
Closing
streams
•
Marking positions
in streams
•
Skipping
ahead in streams
•
Finding
the number of bytes in stream
•
and many
more…
Some input stream methods
DataInputStream
readShort(
) |
readDouble(
) |
readInt( ) |
readLine(
) |
readLong(
) |
readChar(
) |
readFloat(
) |
readBoolean(
) |
readUTF( ) |
Reading from Keyboard
Example
43.1: Reading String, Integer and Double from Keyboard
Example
43.2: Calculator using DataInputStream
Example 43.3: Reading bytes from a file and display data
Example
43.4: Using methods of the FileInputStream class
Byte Output Stream Classes
Hierarchy of OutputStream
OutputStream class is an abstract class. It is the superclass of
all classes representing an output stream of bytes. An output stream accepts
output bytes and sends them to some sink.
public abstract class OutputStream extends Object implements Closeable, Flushable
OutputStream classes
Class |
Description |
The class implements a buffered
output stream. |
|
This class implements an output
stream in which the data is written into a byte array. |
|
A data output stream lets an
application write primitive Java data types to an output stream in a portable
way. |
|
A file output stream is an output
stream for writing data to a File or to a FileDescriptor. |
|
An ObjectOutputStream writes
primitive data types and graphs of Java objects to an OutputStream. |
Use of class OutputStream
Methods of OutputStream class
Method |
Description |
close() |
Closes this output stream and
releases any system resources associated with this stream. |
flush() |
Flushes this output stream and
forces any buffered output bytes to be written out. |
write(byte[] b) |
Writes b.length bytes
from the specified byte array to this output stream. |
write(byte[] b, int off,
int len) |
Writes len bytes from
the specified byte array starting at offset off to this output
stream. |
write(int b) |
Writes the specified byte to this
output stream. |
OutputStream classes is used to write 8-bit bytes and
supports a number of input-related methods
•
Writing
bytes
•
Closing
streams
•
Flushing
streams
•
etc.
DataOutputStream
writeShort( ) |
writeDouble( ) |
writeInt( ) |
writeLine( ) |
writeLong( ) |
writeChar( ) |
writeFloat( ) |
WriteBoolean( ) |
writeUTF( ) |
Example
43.5: Storing data into a File
Example
43.6: Copying bytes from one file to another
Note:
•
Closing
a stream when it's no
longer needed is very important.
•
Always
make sure that each stream variable contains an object reference before
invoking close.
•
Using
Bytes is a kind
of low-level I/O that should be avoided. Since for character data, the best
approach is to use character streams. There are also streams for more
complicated data types.
•
Byte
streams should only be used for the most primitive I/O.
•
All
other stream types are built on byte streams.
IO with Character Streams
Character Stream Classes
•
In
Western locales, the local character set is usually an 8-bit superset of ASCII.
•
The
Java platform stores character values using Unicode conventions.
•
Character
stream I/O automatically translates this internal format to and from the local
character set.
Taxonomy: Java stream classes
Character stream
classes is used to read and write characters and supports a number of
input-output related methods
Ø Reader stream classes
•
To
read characters from files.
•
In
many way, identical to InputStream classes.
Ø Writer stream classes
•
To
write characters into files.
•
In
many way, identical to OutputStream classes.
Reader Stream Classes
•
Abstract
class for reading character streams.
public abstract class Reader extends Object implements Readable, Closeable
•
The
only methods that a sub class must implement are read(char[], int, int) and
close().
•
Most
sub classes, however, will override some of the methods defined here in order
to provide higher efficiency, additional functionality, or both.
Different classes under the Reader class
Method |
Description |
Reads text from a character-input
stream, buffering characters so as to provide for the efficient reading of
characters, arrays, and lines. |
|
This class implements a character
buffer that can be used as a character-input stream. |
|
An InputStreamReader is a bridge
from byte streams to character streams: It reads bytes and decodes them into
characters using a specified charset. |
|
Piped character-input streams. |
|
Abstract class for reading
filtered character streams. |
|
A character-stream reader that
allows characters to be pushed back into the stream. |
|
A character stream whose source is
a string. |
|
A buffered character-input stream
that keeps track of line numbers. |
|
Convenience class for reading
character files. |
Constructors and Fields in Reader class
Fields |
|
Field |
Description |
protected Object lock |
The object used to synchronize operations on this stream. |
Constructor |
Description |
Reader() |
Creates a new character-stream
reader whose critical sections will synchronize on the reader itself. |
Reader(Object lock) |
Creates a new character-stream
reader whose critical sections will synchronize on the given object. |
Methods in Reader class
Method |
Description |
close() |
Closes the stream and releases any
system resources associated with it. |
mark(int readAheadLimit) |
Tells whether this stream supports
the mark() operation. |
markSupported() |
Tells whether this stream supports
the mark() operation. |
read() |
Reads a single character. |
read(char[] cbuf) |
Reads characters into an array. |
read(char[] cbuf, int off, int
len) |
Reads characters into a portion of
an array. |
read(CharBuffer target) |
Attempts to read characters into
the specified character buffer. |
ready() |
Tells whether this stream is ready
to be read. |
reset() |
Resets the stream. |
skip(long n) |
Skips characters. |
Example
44.1: Reading String, Integer and Double from Keyboard
Example
44.2: Calculator using BufferedReader
Writer Stream Classes
•
Abstract
class for writing character streams.
public abstract class Writer extends Object implements Appendable, Closeable, Flushable
•
The
only methods that a subclass must implement are write(char[], int, int),
flush(), and close().
•
Most
subclasses, however, will override some of the methods defined here in order to
provide higher efficiency, additional functionality, or both.
Sub classes of the Writer class
Class |
Description |
Writes text to a character-output
stream, buffering characters so as to provide for the efficient writing of
single characters, arrays, and strings. |
|
This class implements a character
buffer that can be used as an Writer. |
|
Piped character-output streams. |
|
A character stream that collects its
output in a string buffer, which can then be used to construct a string. |
|
Convenience class for writing
character files. |
|
Abstract class for writing
filtered character streams. |
|
Prints formatted representations
of objects to a text-output stream. |
Constructors and Fieldsin Writer class
Fields |
|
Field |
Description |
protected Object lock |
The object used to synchronize operations on this stream. |
Constructor |
Description |
Writer() |
Creates a new character-stream
writer whose critical sections will synchronize on the writer itself. |
Writer(Object lock) |
Creates a new character-stream
writer whose critical sections will synchronize on the given object. |
Example
44.3: Copying files using FileReader and FileWriter
CopChars
versus CopyBytes
•
CopyChars is very similar to CopyBytes.
The most important difference is that CopyChars uses FileReader
and FileWriter for input and output in place of FileInputStream
and FileOutputStream.
•
Both
CopyBytes and CopyChars use an int variable to read to and write from.
•
In
CopyChars, the int variable holds a character value in its last 16 bits;
•
In
CopyBytes, the int variable holds a byte value in its last 8 bits.
Summary
of Java Streams: List of important tasks and their classes
Task |
Character
Stream Class |
Byte Stream
Class |
Performing
input operations Buffering
input Keeping
track of line numbers Reading
from an array Translating
byte stream into a character stream Reading
from files Filtering
the input Pushing
back characters/bytes Reading
from a pipe Reading
from a string Reading
primitive types Performing
output operations Buffering
output Writing to
an array Filtering
the output Translating
character stream into a byte stream Writing to
a file Printing
values and objects Writing to
a pipe Writing to
a string Writing
primitive types |
Reader BufferedReader LineNumberReader CharArrayReader InputStreamReader FileReader FilterReader PushbackReader PipedReader StringReader (none) Writer BufferedWriter CharArrayWriter FilterWriter OutputStreamWriter FileWriter PrintWriter PipedWriter StringWriter (none) |
InputStream
BufferedlnputStream
LineNumberlnputStream
ByteArrayInputStream
(none) FileInputStream
FilterlnputStream
PushbackInputStream
PipedInputStream
StringBufferInputStream
DataInputStream
OutputStream
BufferedOutputStream
ByteArrayOutputStream
FilterOutputStream
(none) FileOutputStream
PrintStream
PipedOutputStream
(none) DataOutputStream |
le Input-Output
Java File I/O
Java provides java.io package which includes numerous class
definitions and methods to manipulate file and flow of data (called File I/O streams)
There are four major classes:
•
File
•
FileInputStream
•
FileOutputStream
•
RandomAccessFile
Using
class File
Using
class File
Example
45.1: Knowing information about a File object
Example
45.2: Storing and reading data in the same file
Example
45.3: Concatenation and buffering
Example
45.4: Interactive input and output
Graphical input and
output
Example
45.5: Graphical input and output
Random Access File
Taxonomy
of RandomAccessFile class
This
class is used for reading and writing to random access file.
•
A random
access file behaves like a large array of bytes.
•
There is a
cursor implied to the array called file pointer, by moving the cursor we do the
read write operations.
•
If
end-of-file is reached before the desired number of byte has been read than
EOFException is thrown. It is a type of IOException.
Constructors
of RandomAccessFile class
Constructor |
Description |
RandomAccessFile(File file, String mode) |
Creates a random access file
stream to read from, and optionally to write to, the file specified by the
File argument. |
RandomAccessFile(String name, String mode) |
Creates a random access file
stream to read from, and optionally to write to, a file with the specified
name. |
Methods
of RandomAccessFile class
Method |
Description |
close() |
It closes this random access file
stream and releases any system resources associated with the stream. |
getChannel() |
It returns the unique FileChannel object
associated with this file. |
readInt() |
It reads a signed 32-bit integer
from this file. |
readUTF() |
It reads in a string from this
file. |
seek(long pos) |
It sets the file-pointer offset,
measured from the beginning of this file, at which the next read or write
occurs. |
writeDouble(double v) |
It converts the double argument to
a long using the doubleToLongBits method in class Double, and then writes
that long value to the file as an eight-byte quantity, high byte first. |
writeFloat(float v) |
It converts the float argument to
an int using the floatToIntBits method in class Float, and then writes that
int value to the file as a four-byte quantity, high byte first. |
write(int b) |
It writes the specified byte to
this file. |
read() |
It reads a byte of data from this
file. |
length() |
It returns the length of this file. |
seek(long pos) |
It sets the file-pointer offset,
measured from the beginning of this file, at which the next read or write
occurs. |
Usefulness
of class RandomAccessFile
•
As the
name implies the class RandomAccessFile allows us to handle a file randomly in
contrast to sequentially in InputStream or OutputStream classes.
•
It allows
to move file pointer randomly.
•
Moreover,
it allows read or write or read-write simultaneously.
Reading from a RAF
Methods
used to read RAF
Method |
Description |
read() |
It reads a byte of data from this
file. |
length() |
It returns the length of this
file. |
seek(long pos) |
It sets the file-pointer offset,
measured from the beginning of this file, at which the next read or write
occurs. |
close() |
It closes this random access file
stream and releases any system resources associated with the stream. |
getChannel() |
It returns the unique FileChannel object
associated with this file. |
readInt() |
It reads a signed 32-bit integer
from this file. |
readUTF() |
It reads in a string from this
file. |
Example
46.1: Reading from a RAF
Writing into a RAF
Methods
to write into RAF
Method |
Description |
write(int b) |
It writes the specified byte to
this file. |
length() |
It returns the length of this
file. |
seek(long pos) |
It sets the file-pointer offset,
measured from the beginning of this file, at which the next read or write
occurs. |
close() |
It closes this random access file
stream and releases any system resources associated with the stream. |
writeDouble(double v) |
It converts the double argument to
a long using the doubleToLongBits method in class Double, and then writes
that long value to the file as an eight-byte quantity, high byte first. |
writeFloat(float v) |
It converts the float argument to
an int using the floatToIntBits method in class Float, and then writes that
int value to the file as a four-byte quantity, high byte first. |
write(int b) |
It writes the specified byte to
this file. |
Example
46.2: Writing into a RAF
Example
46.3: Reading and writing RAF
Example
46.4: Appending to a RAF
Example
46.4: Appending to a RAF
Consider
the Student class for both Read and Write Operations.
Example
46.5: Reading and writing objects (create objects and writing)
Example
46.6: Reading and writing objects (reading objects from file)